import { useEffect } from "react"
import _ from "lodash"

export default function useInfiniteData(list, setList) {
  useEffect(() => {
    const handleScroll = _.debounce(() => {
      if (
        window.pageYOffset + window.innerHeight >=
        document.body.offsetHeight + 10
      ) {
        console.log("到达底部")
        const i = list[list.length - 1] // 最后一个为下标
        const newList = [...list]
        for (let k = i + 1; k <= i + 10; k++) {
          newList.push(k)
        }
        setList(newList)
      }
    }, 100) // 100ms 节流间隔

    window.addEventListener("scroll", handleScroll)

    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [list, setList]) // 这里list和setList不能丢的。
}
